package utils

import (
	"fmt"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"myproject/backend/models"
	"os"
	"sync"
	"time"
)

var sqliteDb *gorm.DB
var dbOnce sync.Once

func initDb() {
	if _, err := os.Stat("./wails.db"); err != nil {
		if os.IsNotExist(err) {
			log.Printf("文件不存在: ./wails.db")
		} else {
			log.Printf("文件检查错误: %v", err)
		}
	} else {
		log.Printf("文件存在: ./wails.db")
	}

	// 检查文件权限
	if info, err := os.Stat("./wails.db"); err == nil {
		log.Printf("文件权限: %v", info.Mode())
	}

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold: time.Second,
			LogLevel:      logger.Info,
			Colorful:      true,
		},
	)
	db, err := gorm.Open(sqlite.Open("wails.db"), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		fmt.Println(err)
		panic("failed to connect database")
	}
	// 执行迁移
	err = db.AutoMigrate(&models.User{}, &models.Customers{})

	if err != nil {
		panic("failed to migrate database")
	}
	sqliteDb = db
}

func GetDB() *gorm.DB {
	dbOnce.Do(initDb)
	return sqliteDb
}
